package com.gdcp.service.impl;

import com.gdcp.beans.Comment;
import com.gdcp.beans.User;
import com.gdcp.common.ResponseModel;
import com.gdcp.common.page.PageBean;
import com.gdcp.mapper.CommentMapper;
import com.gdcp.config.annotation.RedisCache;
import com.gdcp.config.RequestHolder;
import com.gdcp.util.IpUtil;
import com.gdcp.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentMapper commentMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ResponseModel responseModel;

    @Override
    public Map<String,Object> insert(Comment comment) {
        try{
            commentMapper.insert(comment);
        }catch (Exception e){
            e.printStackTrace();
            return responseModel.setModel(false,"评论失败,参数错误");
        }
        return responseModel.setModel(true,"评论成功");
    }

    @Override
    public List<Comment> queryListByProductId(Integer id) {
        List<Comment> comments=commentMapper.queryListByProductId(id);
        if (comments==null){
            return null;
        }
        return comments;
    }

    @Override
    public Comment queryInfoById(Integer user_id, Integer product_id, Integer id) {
        return commentMapper.queryInfoById(user_id, product_id, id);
    }

    @Override
    @RedisCache(flush = true)
    public int doSupport(Integer cid) {
        String key = IpUtil.getRealIp(RequestHolder.getRequest()) + "_doSupport_" + cid;
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(key)) {
            return 0;
        }
        try{
            commentMapper.doSupport(cid);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }

        operations.set(key, cid, 1, TimeUnit.HOURS);
        return 1;
    }

    @Override
    @RedisCache(flush = true)
    public int doOppose(Integer cid) {
        String key = IpUtil.getRealIp(RequestHolder.getRequest()) + "_doOppose_" + cid;
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(key)) {
            return 0;
        }
        try{
            commentMapper.doOppose(cid);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        operations.set(key, cid, 1, TimeUnit.HOURS);
        return 1;
    }

    //@Override
    //public List<Comment> queryListByUID(Integer id) {
    //    return commentMapper.queryListByUID(id);
    //}

    @Override
    public int deleteById(Integer id) {
        try{
            commentMapper.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public Map<String, Object> findPageBreakByCondition(Map<String, Object> model, Integer shop_id) {
        //bootstrap-table要求服务器返回的json须包含：totlal，rows
        Map<String,Object> result = new HashMap<>();
        int total=commentMapper.findPageBreakByConditionByShopId(shop_id).size();
        List<Comment> rows=commentMapper.findPageBreakByCondition(model);
        if (rows.size()==0){
            int count= (int) model.get("a");
            count=count-(int) model.get("b");
            if (count>=0) {
                model.put("a", count);
                rows = commentMapper.findPageBreakByCondition(model);
            }
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    @Transactional(rollbackFor = { Exception.class })
    public Map<String, Object> removeByPrimaryKey(Integer[] ids) {
        try{
            for (Integer id:ids) {
                commentMapper.removeByPrimaryKey(id);
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseModel.setModel(false,"删除["+ids.length+"条记录失败"+e.toString());
        }

        return responseModel.setModel(true,"成功删除["+ids.length+"条记录");
    }

    @Override
    public Map<String,Object> updateInformation(Comment comment) {
        try{
            commentMapper.updateByPrimaryKey(comment);
        }catch (Exception e){
            e.printStackTrace();
            return responseModel.setModel(false,"修改失败");
        }

        return responseModel.setModel(true,"修改成功");
    }

    @Override
    public Comment getInformation(Integer id) {
        //查询父评论
        Comment comment=commentMapper.getInformation(id);
        //父评论，查询子评论
        Comment comment1=commentMapper.queryInfoByParentId(comment.getId());

        //情景一：
        //点击第一层，获取comment---如果为获取的的子评论不为空，那么添加进去
        //评论的父评论为0，那么就是第一层
        if (comment1!=null){
            //System.out.println(comment1);
            comment.setReply(comment1.getContent());
            return comment;
        }

        if (comment.getParent_id()==0){
            return comment;
        }

        //comment.setReply(comment1==null?null:comment.getContent());
        //return comment;
        //第二层判断
        comment.setReply("该评论为店家回复，请勿填写回复");
        return comment;
    }

    @Override
    public Map<String, Object> searchInformation(Map<String, Object> model) {
        Map<String,Object> result = new HashMap<>();
        int total=commentMapper.searchInformation(null).size();
        List<Comment> rows=commentMapper.searchInformation(model);

        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    /*@Override
    public int queryByParentId(Integer parent_id) {
        return commentMapper.queryByParentId(parent_id).size();
    }*/

    @Override
    public Comment queryInfoByParentId(Integer parent_id) {
        return commentMapper.queryInfoByParentId(parent_id);
    }

    @Override
    public PageBean<Comment> queryByPage(Integer user_id, int pc) {
        PageBean<Comment> pb = new PageBean<>();
        pb.setPc(pc);

        int ps = 5;
        pb.setPs(ps);

        //获取总数----直接一次性获取发送过来
        int tr=commentMapper.getPageNumber(user_id).size();
        pb.setTr(tr);

        pb.setTp(pb.getTp());

        //分页查询
        List<Comment> comments=commentMapper.queryByPage(user_id, (pc-1)*ps, ps);
        pb.setBeanList(comments);
        return pb;
    }

    @Override
    public Map<String, Object> findAll(Map<String, Object> model) {
        Map<String,Object> result = new HashMap<>();
        int total=commentMapper.findPageBreakByConditionByShopId(null).size();
        List<Comment> rows=commentMapper.findAll(model);
        if (rows.size()==0){
            int count= (int) model.get("a");
            count=count-(int) model.get("b");
            if (count>=0) {
                model.put("a", count);
                rows = commentMapper.findAll(model);
            }
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public Map<String, Object> searchInformationByShopId(Map<String, Object> model, Integer shop_id) {
        Map<String,Object> result = new HashMap<>();
        int total=commentMapper.findPageBreakByConditionByShopId(shop_id).size();
        List<Comment> rows=commentMapper.searchInformationByShopId(model);
        if (rows.size()==0){
            int count= (int) model.get("a");
            count=count-(int) model.get("b");
            if (count>=0) {
                model.put("a", count);
                rows = commentMapper.searchInformationByShopId(model);
            }
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public Comment getInformationByParentId(Integer id) {
        return commentMapper.getInformationByParentId(id);
    }

    @Override
    public Comment getInformationByOrderItemId(Integer id) {
        //查询父评论
        Comment comment=commentMapper.getInformationByOrderItemId(id);
        if (comment!=null){
            //父评论，查询子评论
            Comment comment1=commentMapper.queryInfoByParentId(comment.getId());
            comment.setReply(comment1==null?null:comment1.getContent());
        }
        return comment;
    }
}
